import { useUserStoreWithOut } from '@/store/modules/user'
import * as mainRouter from '@/router/routes/modules/router'
import { isArray, isString } from '@/utils/is'
import { LayoutMenu } from "@/layouts/hooks/getLayoutMenu";

export function setRootPathByPermission( { from } ): string {
    const layoutMenu = new LayoutMenu();
    const routerMap = isArray(mainRouter.default) ? mainRouter.default : [mainRouter.default]
    // 默认进入无权限页面
    let result = "/:productCode/:tenantCode" + import.meta.env.VITE_PUBLIC_PATH + "/403";
    const userStore = useUserStoreWithOut()
    const permissionCodeMap = userStore.getPermissionMap
    const path = iterationMenu(routerMap, permissionCodeMap);
    if (path) {
        result = path
    }
    // 如果包括参数，通过route无法匹配，此处再次通过layoutMenu查找
    if (layoutMenu && layoutMenu.codePathMap) {
      const { codePathMap } = layoutMenu;
      for (let key of codePathMap.keys()) {
        if (permissionCodeMap?.includes(key) && codePathMap.get(key)?.path) {
          result = codePathMap.get(key).path;
          break;
        }
      }
    }
    result = getPathWithCode(result, from);
    return result
}

function iterationMenu(menu: any, permissionCodeMap: any): string {
    for (const item of menu) {
        if (item.children && item.children.length) {
            const _deepPath = iterationMenu(item.children, permissionCodeMap)
            // 直接返回会引起二级菜单没匹配到的时，不继续匹配的问题
            if (_deepPath) {
                return _deepPath
            }
        }
        if (permissionCodeMap?.includes(item.meta.code)) {
            return item.path
        }
    }
    return ''
}


export function getPathWithCode(url: string, from) {
  const userStore = useUserStoreWithOut();
  let { productCode, tenantCode } = userStore;
  if (!productCode && !tenantCode && from) {
    productCode = from.params?.productCode;
    tenantCode = from.params?.tenantCode;
  }

  if (!productCode || !tenantCode) {
    productCode = "";
    tenantCode = "";
  } else {
    productCode = "/" + productCode;
    tenantCode = "/" + tenantCode;
  }

  return url
    .replace("/:productCode", productCode)
    .replace("/:tenantCode", tenantCode);
}


export function recursionRoutes(routes) {
  routes.forEach((routeItem) => {
    routeItem.path && (routeItem.path = routeItem.path.replace("/:productCode/:tenantCode", ""));
    routeItem.redirect &&
    isString(routeItem.redirect) &&
    (routeItem.redirect = routeItem.redirect.replace("/:productCode/:tenantCode", ""));
    if (routeItem.children) {
      resetRoutePath(routeItem.children);
    }
  });
}

// 根据打开的域名，重置Routes
export function resetRoutePath(routes) {
  // 判断是否是包括二级域名
  const { pathname } = window.location;
  const microAppData = window.microApp?.getData() ?? window.eventCenterForViteApp?.getData();
  let realPathname = pathname;
  // 如果嵌在微应用里
  if (microAppData && microAppData.baseroute) {
    realPathname = realPathname.replace(microAppData.baseroute, "");
  }
  //兼容ProductContainer中配域名后直接调用的情况
  if (realPathname.startsWith("/app_") || realPathname.startsWith("/allin-app/app_")) {
    recursionRoutes(routes);
  }
}
